import { defineStore } from 'pinia'
import type { PatrolClassEvent } from '../types/PatrolClassEvent'

/**
 * 巡课事件存储模块
 * 负责管理巡课事件的全局状态
 */
export const usePatrolClassEventStore = defineStore('patrolClassEvent', {
    state: () => ({
        // 所有巡课事件列表
        events: [] as PatrolClassEvent[],
        // 当前选中的事件
        currentEvent: null as PatrolClassEvent | null,
        // 加载状态
        loading: false,
        // 时间范围筛选
        timeRange: {
            start: null as string | null,
            end: null as string | null
        }
    }),
    actions: {
        /**
         * 获取所有巡课事件
         */
        async fetchAllEvents() {
            this.loading = true
            try {
                // this.events = await eventApi.getAllPatrolClassEvents()
            } finally {
                this.loading = false
            }
        },

        /**
         * 创建新的巡课事件
         * @param newEvent - 新巡课事件对象
         */
        async createEvent(newEvent: Omit<PatrolClassEvent, 'patrolClassEventId'>) {
            this.loading = true
            try {
                // const created = await eventApi.createPatrolClassEvent(newEvent)
                // this.events.unshift(created)
            } finally {
                this.loading = false
            }
        },

        /**
         * 设置时间范围筛选
         * @param start - 开始时间
         * @param end - 结束时间
         */
        setTimeRange(start: string | null, end: string | null) {
            this.timeRange = { start, end }
        }
    },
    getters: {
        /**
         * 获取筛选后的事件列表
         */
        filteredEvents(state): PatrolClassEvent[] {
            let result = [...state.events]

            if (state.timeRange.start) {
                result = result.filter(e => e.patrolTime >= state.timeRange.start!)
            }

            if (state.timeRange.end) {
                result = result.filter(e => e.patrolTime <= state.timeRange.end!)
            }

            return result.sort((a, b) =>
                new Date(b.patrolTime).getTime() - new Date(a.patrolTime).getTime()
            )
        },

        /**
         * 获取即将进行的巡课事件
         */
        upcomingEvents(state): PatrolClassEvent[] {
            const now = new Date()
            return state.events
                .filter(e => new Date(e.patrolTime) > now)
                .slice(0, 5)
        }
    }
})
